const dgram = require('dgram')

class MyUdpSocket {
  static client_port;
  static client_ip;

  channel;
  pkg_list = [];


  constructor() {
    this.channel = dgram.createSocket('udp4')
    this.channel.bind(33001, '192.168.6.12')
    this.channel.connect(6666, '192.168.6.99', () => {
      this.channel.addListener('message', (packet) => {this.get_receive_packet(packet,this)})
    })
  }

  
  start(list) {
    this.pkg_list = [...list]
    this.send()
  }

  send(temp) {
    // let temp = this.pkg_list.pop()
    // console.log(temp)
    setTimeout(() => {
      const rinfo = this.channel.remoteAddress();
      this.channel.send(temp, rinfo.port, rinfo.address);
    })
  }


  receive() {
    if(this.bool) {
      let temp = new Buffer.alloc(this.receive_buffer.length);
      for (let i = 0; i < temp.length; i++) {
        temp[i] =  this.receive_buffer[i]
      }
      this.receive_buffer = new Buffer.alloc(0);
      this.bool = false
      return temp
    }
  }

  get_receive_packet(packet, that) {
    console.log(packet, packet[11])
    // that.send()
    if(packet[11] === 1) {
     
    }
    // that.receive_buffer = new Buffer.alloc(packet.length);
    // for (let i = 0; i < packet.length; i++) {
    //   that.receive_buffer[i] = packet[i]
    // }
    // that.bool = true
  }
}

module.exports = {
  MyUdpSocket
}

